/* eslint-disable */
import axios from 'axios';
import store from '@/store';
import router from '@/router/index'
import { Message } from 'element-ui'

// import router from '@/router/index'
// import {getToken} from '@/utils/auth'
// 全局设置axios
// axios.defaults.headers.post['Content-type'] = 'application/json;charset=UTF-8';// 请求头
// axios.defaults.headers.post['Content-type'] =  'multipart/form-data';// 请求头
axios.defaults.baseURL = process.env.BASE_API; // 服务器接口地址发生改变,数据请求接口地址
axios.defaults.timeout = 30000; // 请求超时时间
axios.defaults.withCredentials=true;
if (store.getters.token != 'null') {  
    if(store.getters.token == null){     
        axios.defaults.headers.token = '';
    }   else {      
        axios.defaults.headers.token = store.getters.token.replace(/""/, '');
    }
 
} else {
  axios.defaults.headers.token = '';
}
// Axios错误数据拦截
axios.interceptors.response.use(
  response => { 
      if (response.data) {
        switch (response.data.ret) {
          case 402:
          Message('登录失效,请重新登');
            store.dispatch('logOut').then(() => {
                setTimeout(()=>{
                router.openPage('/login')
                },500)
            });
            break;
        }
      }
    return response
  },
  (error) => {
    Promise.reject(error);
  });
const request = (method, url, data, config = {}) => {
  const options = Object.assign({}, config, {
    url,
    method,
    data
  });
  options.headers = options.headers || {};

  return new Promise((resolve, reject) => {
    axios.request(options)
      .then((res) => {
        const data = {};
        if (res) {
          const data = {
            headers: res.headers,
            data: res.data
          };
          resolve(data);
        }
      }).catch((error) => { 
        // 在这里做错误处理
        reject(error);
      });
  });
};

// 封装axios方法
export const fetch = {
  get(url, config) {
    return request('get', url, null, config);
  },
  post(url, data, config) {
    return request('post', url, data, config);
  },
  put(url, data, config) {
    return request('put', url, data, config);
  },
  delete(url, data, config) {
    return request('delete', url, data, null, config);
  },
  head(url, config) {
    return request('head', url, null, config);
  },
  patch(url, data, config) {
    return request('patch', url, data, config);
  }
};
